import express from 'express'
import schedule from 'node-schedule'
import { parseToken } from '../../../util/common.js'
import { addSql, detailSql, getResult, listSql, putSql } from '../../../util/operateSql.js'
import { postWeixin } from '../../../api/robot/weixin.js'
import globalCache from '../../../cache.js'
var router = express.Router()


const NAMESPACE = 'schedule_job'

const table = 'robot.schedule_jobs'

// *  *  *  *  *  *
// ┬  ┬  ┬  ┬  ┬  ┬
// │  │  │  │  │  |
// │  │  │  │  │  └ 星期几，取值：0 - 7，其中 0 和 7 都表示是周日
// │  │  │  │  └─── 月份，取值：1 - 12
// │  │  │  └────── 日期，取值：1 - 31
// │  │  └───────── 时，取值：0 - 23
// │  └──────────── 分，取值：0 - 59
// └─────────────── 秒，取值：0 - 59（可选）

// 当前时间的秒值为 10 时执行任务，如：2018-7-8 13:25:10
// let job = schedule.scheduleJob('10 * * * * *', () => {
//   
// });

// 或者未来某个时间
// let date = new Date(2016, 6, 13, 15, 50, 0);
// let job = schedule.scheduleJob(date, () => {
//   
// });


// 任务体
const josFunc = (message) => {
  return () => {
    postWeixin({
      msgtype: "text",
      text: {
        content: message
      }
    })
  }
}

// 检查是否存在
const checkJobName = (req,res,next) => {
  const key = parseToken(req.headers.authorization)
  const name = `${key}_${req.body.name}`
  const sql = detailSql(table,{name})
  getResult(sql).then((result) => {
    req.hasExsit = !!result.length
    next()
  })
}

/**
 * @param {number} type 任务类型 0: 定时任务 1: 循环任务
 * @param {number} open 任务开关 0: 关闭 1: 开启
 * 新建定时发送消息
 */
router.post('/message', checkJobName,(req, res, next) => {

  const key = parseToken(req.headers.authorization)
  const type = +req.body.type // 任务类型
  const date = +type ? req.body.date : new Date(req.body.date) // 任务日期
  const name = req.body.name || new Date().getTime() // 任务名
  const message = req.body.content || ''

  const hasJob = globalCache.getCache(NAMESPACE, `${key}_${name}`)
  if (req.hasExsit) {
    res.send(req.app.locals.error('任务名已存在'))
    return
  } 


  let job = schedule.scheduleJob(`${key}_${name}`, date, josFunc(message))

  globalCache.setCache(NAMESPACE, `${key}_${name}`, req.body)
  const sql = addSql(table, { name: `${key}_${name}`, date: date, content: message, status: 1 })

  getResult(sql).then((result) => {
    res.send(req.app.locals.success('定时任务开启成功'))
  }).catch((err) => {
    res.send(req.app.locals.error(err))
  });


})


// 开启/关闭任务
router.post('/edit',(req,res,next) => {
  const id = +req.body.id
  const isOpen = +req.body.isOpen
  const sql = putSql(table, {status: isOpen},{id})
  getResult(sql).then((result) => {
    res.send(req.app.locals.success('定时任务关闭成功'))

  }).catch((err) => {
    res.send(req.app.locals.error(err))

  });
})



// 开启/取消所有任务
router.post('/all', async (req, res, next) => {
  const key = parseToken(req.headers.authorization)
  const open = +req.body.isOpen
  if (!open) {
    await schedule.gracefulShutdown()
    const sql = putSql(table, { status: 0 })
    try {
      getResult(sql).then((result) => {
        res.send(req.app.locals.success('success'))
      })
    } catch (error) { 
      res.send(req.app.locals.error(error))
    }
  } else {
    const openSql = putSql(table, { status: 1 })
    getResult(openSql)
    const sql = listSql(table, { pageSize: 1000, pageIndex: 1 })
    getResult(sql).then((result) => {
      const rows = result    
      console.log('rows: ', rows);
      for (let i = 0; i < rows.length; i++) {
        schedule.scheduleJob(`${rows[i].name}`, rows[i].date, josFunc(rows[i].content))        
      }
      console.log('schedule.scheduledJobs: ', schedule.scheduledJobs);
      res.send(req.app.locals.success(Object.keys(schedule.scheduledJobs)))

    })
  }
})


// 任务列表

router.get('/list', async (req, res, next) => {
  const sql = listSql(table, { pageSize: 20, pageIndex: 1 })

  try {
    const row = await getResult(sql)

    res.send(req.app.locals.success(row))
  } catch (error) {

    res.send(req.app.locals.error(error))
  }
})


// 真实任务列表
router.get('/realList', async (req, res, next) => {

  try {
    const rows = schedule.scheduledJobs
    res.send(req.app.locals.success(Object.keys(rows)))
  } catch (error) {
    console.log('error: ', error);

    res.send(req.app.locals.error(error))
  }
})


export default router